class Store {


	constructor() {
		// 检测是否支持localstorage
		this.own = 1;
		this.store = null;
		if (uni != undefined) {
			this.store = uni;
			this.own = 1;
		} else if (window !== undefined && window.localStorage) {
			this.own = 2;
			this.store = window.localStorage;
			//	console.log(2.1)
		} else if (localStorage) {
			this.own = 2;
			this.store = localStorage;
			//console.log(2.2)
		} else{
			console.log('不支持localStorage')
			this.own = 0;
		}
	
	}

	/**
	 * @function 设置值
	 * @param {string} _k 必须参数，属性
	 * @param {any} _v 非必须参数，属性值
	 */
	set(key, _v) {
		let vau = this.filterValue(_v);
			//console.log(this.own,key, vau)
		if (this.own == 1) {
			//console.log(key, vau)
			this.store.setStorageSync(key, vau)
		} else if (this.own == 2){		
			this.store.setItem(key, vau)
		} 
	}

	/**
	 * @function 获取值
	 * @param {string} _k 必须参数，属性
	 */
	get(key) {
		if (this.own == 1){
			return this.store.getStorageSync(key);
			
		}else if (this.own == 2) {
			return this.store.getItem(key);
		}
		
		return null
	}

	/**
	 * @function 移除值
	 * @param {string} _k 必须参数，属性
	 */
	remove(key) {
		if (this.own == 1){			
			return this.store.removeStorageSync(key);
		}	else if (this.own == 2) {
			return this.store.removeItem(key);
		}
	}

	/**
	 * @function 移除所有
	 */
	clear() {
		if (this.own == 1)
			return this.store.clearStorageSync();
			
		else if (this.own == 2) {
			return this.store.clear();
		}
	}

	/**
	 * @function 判断类型
	 * @param {any} para 必须参数，判断的值
	 */
	getType(para) {
		let type = typeof para
		if (type === 'number' && isNaN(para)) return 'NaN'
		if (type !== 'object') return type
		return Object.prototype.toString
			.call(para)
			.replace(/[\[\]]/g, '') // eslint-disable-line
			.split(' ')[1]
			.toLowerCase()
	}

	/**
	 * @function 过滤值
	 * @param {any} val 必须参数，过滤的值
	 */
	filterValue(val) {
		let vType = this.getType(val)
		let nullVal = ['null', 'undefined', 'NaN']
		let stringVal = ['boolean', 'number', 'string']
		if (nullVal.indexOf(vType) >= 0) return ''
		if (stringVal.indexOf(vType) >= 0) return val
		return JSON.stringify(val)
	}
}





export default Store
